<!--
 * @Description: 角色管理
 * @Author: HuiSir<https://gitee.com/huisir001>
 * @Date: 2021-09-09 15:14:07
 * @LastEditTime: 2025-09-26 16:20:16
-->
<template>
  <TablePage
    v-model:cols="tableCols"
    v-model:toolsOptions="toolsOptions"
    v-model:rowBtnsOptions="rowBtnsOptions"
    :listRequest="getRolePageList"
    :afterListRequest="afterListRequest"
  >
    <template #permissionIds="scope">
      <!-- default-expand-all -->
      <el-tree
        ref="treeRef"
        :data="permTree"
        show-checkbox
        node-key="id"
        highlight-current
        :props="defaultProps"
        @check="(node: unknown, checkedData: { checkedKeys: string[]; }) => bindTreeCheck(node, checkedData, scope)"
      />
    </template>
  </TablePage>
</template>

<script lang="ts" setup>
import { ref, Ref } from "vue";
import TablePage from "@/components/TablePage/index.vue";
import useTableCols from "./hooks/useTableCols";
import useToolsOptions from "./hooks/useToolsOptions";
import useRowBtnsOptions from "./hooks/useRowBtnsOptions";
import { getRolePageList } from "@/api/sys";
import { project } from "@/init/config";
import { fieldMapping } from "@/utils/common";
import { getPermTree } from "@/api/sys";
import type { TreeInstance } from "element-plus";

// 配置项
defineOptions({ name: "RoleList", isFull: true });

// 树ref
const treeRef = ref<TreeInstance>();

// 数据处理
const afterListRequest = (dataList: Ref<Recordable>) => {
  // 字段映射
  fieldMapping({
    data: dataList.value.records,
    fieldsMap: project.roleFields,
  });
};

const permTree = ref<Permission[]>([]);
const defaultProps = {
  children: "children",
  label: "title",
};

// 请求权限树
const getPermTreeList = async () => {
  if (permTree.value.length) return;
  const { ok, data } = await getPermTree();
  if (ok && data) {
    permTree.value = data;
  }
};

// 手动选中（by key）
const setCheckedKeys = (keys: string[]) => {
  treeRef.value!.setCheckedKeys(keys, false);
};

// 获取选中key
// const getCheckedKeys = () => {
//   return treeRef.value!.getCheckedKeys(false);
// };

// 树组件选中
const bindTreeCheck = (
  _node: unknown,
  checkedData: { checkedKeys: string[] },
  scope: { val: { permissionIds: string[] | null } }
) => {
  scope.val.permissionIds = checkedData.checkedKeys;
};

// 表格配置
const tableCols = useTableCols();
const toolsOptions = useToolsOptions(getPermTreeList);
const rowBtnsOptions = useRowBtnsOptions(getPermTreeList, setCheckedKeys);
</script>
